<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="充值金额" prop="amount">
        <el-input-number
          v-model="formData.amount"
          :min="1"
          :precision="2"
          :step="100"
          placeholder="请输入充值金额"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="满赠金额" prop="bonusAmount">
        <el-input-number
          v-model="formData.bonusAmount"
          :min="0"
          :precision="2"
          :step="10"
          placeholder="请输入满赠金额"
          style="width: 100%;"
        >
          <template #suffix>元</template>
        </el-input-number>
        <div class="el-form-item-msg">充值满多少赠送的金额，0表示无满赠</div>
      </el-form-item>
      <el-form-item label="金额类型" prop="amountType">
        <el-select v-model="formData.amountType" placeholder="请选择金额类型" style="width: 100%;" disabled>
          <el-option label="消费" value="CONSUME" />
          <el-option label="充值" value="RECHARGE" />
        </el-select>
      </el-form-item>
      <el-form-item label="交易方式" prop="transactionChannel">
        <el-select v-model="formData.transactionChannel" placeholder="请选择交易方式" style="width: 100%;">
          <el-option label="支付宝" value="ALIPAY" />
          <el-option label="微信" value="WECHAT" />
          <el-option label="网商银行" value="BANK" />
          <el-option label="现金" value="BALANCE" />
          <el-option label="系统" value="SYSTEM" disabled />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="formData.businessType" placeholder="请选择业务类型" style="width: 100%;">
          <el-option label="爪哇国收银" value="JAVATYPE" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {FinancialFlow, FinancialFlowApi} from '@/api/javainfo/financialflow'

/** 用户充值 弹窗 */
defineOptions({ name: 'UserRechargeDialog' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('用户充值') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const userId = ref<number>() // 用户ID

const formData = ref({
  amount: 100, // 默认100元
  bonusAmount: 0, // 默认无满赠
  amountType: 'RECHARGE', // 默认充值类型
  transactionChannel: 'ALIPAY', // 默认支付宝
  businessType: 'JAVATYPE', // 默认爪哇国收银
  remark: '', // 备注
})

const formRules = reactive({
  amount: [{ required: true, message: '充值金额不能为空', trigger: 'blur' }],
  bonusAmount: [
    { required: true, message: '满赠金额不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '满赠金额必须大于等于0', trigger: 'blur' }
  ],
  amountType: [{ required: true, message: '金额类型不能为空', trigger: 'change' }],
  transactionChannel: [{ required: true, message: '交易方式不能为空', trigger: 'change' }],
  businessType: [{ required: true, message: '业务类型不能为空', trigger: 'change' }],
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  userId.value = id
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 提交请求
  formLoading.value = true
  try {
    // 构建财务流水数据
    const data: FinancialFlow = {
      flowId: undefined, // 新增时不需要ID
      userId: userId.value,
      petId: undefined, // 充值不关联宠物
      orderNumber: generateOrderNumber(), // 生成订单号
      amountType: formData.value.amountType, // 金额类型
      transactionChannel: formData.value.transactionChannel,
      amount: formData.value.amount * 100, // 转换为分
      balanceAfter: undefined, // 后端计算
      businessType: formData.value.businessType,
      relatedId: undefined, // 充值没有关联业务ID
      remark: formData.value.remark || '用户充值',
      bonusAmount: formData.value.bonusAmount * 100, // 满赠金额转换为分
    }

    // 调用API保存数据
    await FinancialFlowApi.createFinancialFlow(data)
    message.success('充值成功')
    dialogVisible.value = false

    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 生成订单号 */
const generateOrderNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')

  return `RC${year}${month}${day}${hour}${minute}${second}${random}`
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    amount: 100,
    bonusAmount: 0,
    amountType: 'RECHARGE',
    transactionChannel: 'ALIPAY',
    businessType: 'JAVATYPE',
    remark: '',
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.el-form-item-msg {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>

